import {
  auth_login,
  getCurrentUserInfo
} from '../../request/api'

import {
  myGet
} from '../../request/index'
import {
  verifyToken
} from '../../utils/authUtil'
import Toast from '@vant/weapp/toast/toast';

Component({
  /**
   * 组件的属性列表
   */
  properties: {},
  /**
   * 组件的初始数据
   */
  data: {
    show: false
  },
  pageLifetimes: {
    show() {
      verifyToken().then(userInfo => {
        if (!userInfo) {
          // this.setData({
          //   show: true
          // })
          this.wxLogin()
        } else {
          this.triggerEvent('loginAfter', userInfo)
        }
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    cancel() {
      this.triggerEvent('cancel');
    },
    wxLogin() {
      wx.login({
        success: res0 => {
          myGet(auth_login, {
            code: res0.code
          }, (res) => {
            if (res.status === 200) {
              wx.setStorageSync('loginCode', res0.code)
              const data = res.data
              wx.setStorageSync('headerInfo', data)
              myGet(getCurrentUserInfo, {}, (res2) => {
                const userInfo = {
                  wechatName: res2.data.wechatName,
                  wechatHeadImage: res2.data.wechatHeadImage
                }
                wx.setStorageSync('userInfo', userInfo)
                this.triggerEvent('loginAfter', userInfo)
              })
            }
          })
        }
      })
    },
    showGetPhoneWind() {
      if (!wx.getStorageSync('phone')) {
        this.setData({
          showGetPhoneWind: true
        })
      }
    },
    onPhoneClose() {
      this.triggerEvent('onPhoneClose', false);
    },
    getPhoneNumber(e) {
      const code = e.detail.code
      if (!code) {
        Toast.fail({
          message: '已取消授权',
          forbidClick: true,
          duration: 1500
        });
        this.triggerEvent('phoneCancel')
        return
      }
      Toast.loading({
        message: '更新中...',
        forbidClick: true,
        duration: 0
      });
      myGet(auth_phone, {
        code: code
      }, (res) => {
        Toast.clear()
        if (res.status === 200) {
          wx.setStorageSync('phone', res.data)
          this.triggerEvent('phoneBinded', res.data)
        }
      })
    },
    showLoading(text) {
      Toast.loading({
        duration: 0,
        message: text,
        forbidClick: true,
      });
    },
    hideLoading() {
      Toast.clear()
    },
    showShowBindWind() {
      this.setData({
        showToBindWind: true
      })
    },
    hideShowBindWind() {
      this.setData({
        showToBindWind: false
      })
    },
    getTopBindPage() {
      wx.navigateTo({
        url: '/pages/user/components/shop-info/shop-info',
      })
    }
  }
})